package com.gax.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gax.utils.JwtHelper;
import com.gax.utils.Result;
import com.gax.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author GAX
 * @date 2025-06-19
 */

@Component
public class LoginProtectedInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtHelper jwtHelperl;

    // 如果 token 有效，则放行，如果无效，则返回 504
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取 token
        String token = request.getHeader("token");
        // 检查是否有效
        boolean expiration = jwtHelperl.isExpiration(token);
        // 有效则放行
        if (!expiration) {
            // 放行，没有过期
            return true;
        }
        // 无效，返回 504 的状态 JSON
        // 业务封装：构造一个统一响应对象，表示“未登录”
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN);
        // 把 Java 对象序列化为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        // 直接把 JSON 写回给客户端
        response.getWriter().print(json);
        // 返回 false，阻止 Spring MVC 继续调用真正的 Controller
        return false;
    }
}
